/**
 * 练习4.模拟微信发红包（手气最佳）
 * 搁置：浮点数精确计算问题
*/

#include <iostream>
#include <time.h>

double get_bonus(double total, int n, double min);

// bonus
int main(void)
{
  // unsigned int seed = (unsigned)time(NULL);
  // srand(seed); // 初始化随机数函数种子
  // // 1632127023
  srand(1632127023);     // 方便调试
  double total = 100.00; // 红包大小
  const int num = 10;    // 发红包的个数
  // const double amount_min = 0.01; // 限制红包最小值

  double const amount_min = total / (double)100; // 假定最小红包为红包总额的1/100;那么发红包数不能超过100个

  std::cout << "红包总额: " << total << " 红包个数: " << num << " 最小红包金额: " << amount_min << std::endl;

  double max = 0.00; // 手气最佳值，最大值
  int max_i = -1;    // 哪个人手气最佳
  double arr[num] = {};

  int i = 0;
  while (total > 0)
  {
    // 最后一人是剩余的值
    double val = 0.00;
    if (i == num - 1)
    {
      // std::cout << "最后一人 " << total << std::endl;
      val = total;
    }
    else
    {
      val = get_bonus(total, (num - i), amount_min);
    }

    // std::cout << "val : " << val << std::endl;

    if (val > max)
    {
      max = val; // 最大值
      max_i = i; // 最大值索引
    }

    arr[i] = val;
    total -= val;
    i++;
  }

  // 输出
  for (i = 0; i < num; i++)
  {
    std::cout << "第" << (i + 1) << "个人抢的红包大小是" << arr[i]
              << "。" << (max_i == i ? "手气最佳!!!" : "") << std::endl;
  }

  printf("----------end-----------\n");
  return 0;
}

/**
 * 抢一个红包
 * total 总红包大小
 * n 剩余可抢数量
 * min 红包最小值，保底数
*/
double get_bonus(double total, int n, double min)
{
  // srand((unsigned)time(NULL));
  double res = 0;
  int range_s = min * (double)100;                             // 可待抢金额范围最小值
  int range_e = (total - (double)(n - 1) * min) * (double)100; // 可待抢金额范围最大值

  if (range_s == range_e)
  {
    std::cout << "->最小值<-" << std::endl;
    res = range_s / (double)100;
  }
  else
  {
    int num = rand() % (range_e - range_s + 1) + range_s;
    // std::cout << "num : " << num << std::endl;
    res = (double)num / (double)100;
  }

  std::cout << "total: " << total << " n: " << n << " range_s: " << range_s << " range_e: " << range_e << " res: " << res << std::endl;

  return res;
}